//202302104036崔晓涵
package cn.edu.sdjzu.xg.eagle.service.impl;

import cn.edu.sdjzu.xg.eagle.dao.StudentDao;
import cn.edu.sdjzu.xg.eagle.entity.ActorType;
import cn.edu.sdjzu.xg.eagle.entity.Student;
import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.DaoFactory;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.StudentService;
import cn.edu.sdjzu.xg.eagle.service.UserService;
import cn.edu.sdjzu.xg.eagle.util.IdUtil;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;

public class StudentServiceImpl implements StudentService {
    static StudentDao studentDao = null;
    static UserService userService = null;
    static {
        try{
            studentDao = DaoFactory.getDao(StudentDao.class,"StudentDaoImpl");
//            actorService = ServiceFactory.getService(ActorService.class, "ActorServiceImpl");
            userService = ServiceFactory.getService(UserService.class, "UserServiceImpl");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public boolean add(Student student) throws SQLException, BaseException, InvocationTargetException {
        Connection connection = null;
        try {
            connection = JdbcHelper.getConn();
            connection.setAutoCommit(false); // 开启事务

            // 使用雪花算法生成Student的id
            Long teacherId = IdUtil.getLongId();
            student.setId(teacherId);

            // 创建User对象，用户名和密码都取自Student的no字段
            User user = new User();
            user.setUsername(student.getNo());
            user.setPassword(student.getNo());
            // 设置User关联的实际参与者类型为Student
            user.setActorType(ActorType.STUDENT);

            // 由于student的id已经赋值，可以让actor字段指向teacher对象
            // User对象关联Student对象
            user.setActor(student);

            // 先添加User对象，因为User的id是数据库自增的,保存到数据库才能得到id
            // 将来都使用应用程序生成id，既适应分布式趋势，持久化操作也简化了
            Integer userId = userService.add(connection, user);
            if (userId == null) {
                throw new BaseException("添加用户失败.");
            }

            // 用新生成的User对象的id来设置User对象的id
            user.setId(userId);

            // Student对象关联User对象
            student.setUser(user);

            // 再持久化student对象，此时它的user字段已经关联了User对象
            boolean isAdded = studentDao.add(connection, student);
            if (!isAdded) {
                throw new BaseException("添加教师失败.");
            }

            connection.commit(); // 提交事务
            return true;
        } catch (SQLException | BaseException | InvocationTargetException e) {
            if (connection != null) {
                connection.rollback(); // 回滚事务
            }
            e.printStackTrace();
            throw new BaseException("数据库操作异常.");
        } finally {
            JdbcHelper.close(connection); // 关闭数据库连接
        }
    }

    @Override
    public boolean delete(Long id) throws SQLException, BaseException {
        Connection connection = null;
        try {
            connection = JdbcHelper.getConn();
            connection.setAutoCommit(false);

            Student student = studentDao.find(connection, id);
            if (student == null) {
                throw new BaseException("学生不存在，删除失败");
            }
            Long userId = student.getUser_id();
            if (userId != null) {
                UserService userService = ServiceFactory.getService(UserService.class, "UserServiceImpl");
                userService.delete(userId);
            }

            boolean isDeleted = studentDao.delete(connection, id);
            if (!isDeleted) {
                throw new BaseException("删除学生信息失败");

            }
            connection.commit();
            return true;
        }catch(SQLException | BaseException|InvocationTargetException e){
            if(connection != null) {
                connection.rollback();
            }
            throw new BaseException("数据库操作异常：" + e.getMessage());

        }finally{
            JdbcHelper.close(connection);
        }
    }
}
